package com.ktjiaoyu.ktmall.dao.impl;

import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.dao.ProductDao;
import com.ktjiaoyu.ktmall.entity.Product;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xm
 * @date 2025/9/15
 * @Dome
 */
public class ProductDaoImpl extends BaseDao implements ProductDao {
    @Override
    public List<Product> findList(String title, Long categoryId, int page, int pageSize) {
        StringBuffer sql = new StringBuffer("SELECT id,title,subtitle,category_id,category_path,brand,main_image,images," +
                "description,price,original_price,stock,sales,`status`,is_deleted," +
                "create_time,update_time FROM `kt_product` WHERE  is_deleted=0 ");
        List<Object> params = new ArrayList<Object>();
        if (title != null && !title.isEmpty()) {
            sql.append(" AND `title` LIKE ? ");
            params.add("%" + title + "%");
        }
        if (categoryId != null) {
            sql.append(" and FIND_IN_SET(?,category_path) ");
            params.add(categoryId);
        }
        sql.append(" ORDER BY create_time DESC limit ?,? ");
        params.add((page - 1) * pageSize);
        params.add(pageSize);
        try {
            return executeQuery(sql.toString(), rs -> {
                List<Product> list = new ArrayList<>();
                try {
                    while (rs.next()) {
                        Product product = new Product();
                        product.setId(rs.getLong("id"));
                        product.setTitle(rs.getString("title"));
                        product.setSubtitle(rs.getString("subtitle"));
                        product.setCategory_id(rs.getLong("category_id"));
                        product.setCategory_path(rs.getString("category_path"));
                        product.setBrand(rs.getString("brand"));
                        product.setMain_image(rs.getString("main_image"));
                        product.setImages(rs.getString("images"));
                        product.setDescription(rs.getString("description"));
                        product.setPrice(rs.getDouble("price"));
                        product.setOriginal_price(rs.getDouble("original_price"));
                        product.setStock(rs.getInt("stock"));
                        product.setSales(rs.getInt("sales"));
                        product.setStatus(rs.getInt("status"));
                        product.setIs_deleted(rs.getInt("is_deleted"));
                        product.setCreate_time(rs.getDate("create_time"));
                        product.setUpdate_time(rs.getDate("update_time"));
                        list.add(product);
                    }
                    return list;
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }, params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public int count(String title, Long categoryId) {
        StringBuffer sql = new StringBuffer("select count(*) from `kt_product` where is_deleted=0 ");
        List<Object> params = new ArrayList<>();
        if (title != null && !title.isEmpty()) {
            sql.append(" and `title` LIKE ? ");
            params.add("%" + title + "%");
        }
        if (categoryId != null) {
            sql.append(" and FIND_IN_SET(?,category_path) ");
            params.add(categoryId);
        }
        try {
            List<Integer> result = executeQuery(sql.toString(), rs -> {
                List<Integer> list = new ArrayList<>();
                try {
                    if (rs.next()) {
                        list.add(rs.getInt(1));
                    }
                    return list;
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }, params.toArray());
            return result.isEmpty() ? 0 : result.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Product findById(Long id) {
        String sql = "SELECT id,title,subtitle,category_id,category_path,brand,main_image,images," +
                "description,price,original_price,stock,sales,`status`,is_deleted," +
                "create_time,update_time FROM `kt_product` WHERE id=? and is_deleted=0 ";
        try {
            List<Product> list = executeQuery(sql, rs -> {
                List<Product> l = new ArrayList<>();
                try {
                    while (rs.next()) {
                        Product product = new Product();
                        product.setId(rs.getLong("id"));
                        product.setTitle(rs.getString("title"));
                        product.setSubtitle(rs.getString("subtitle"));
                        product.setCategory_id(rs.getLong("category_id"));
                        product.setCategory_path(rs.getString("category_path"));
                        product.setBrand(rs.getString("brand"));
                        product.setMain_image(rs.getString("main_image"));
                        product.setImages(rs.getString("images"));
                        product.setDescription(rs.getString("description"));
                        product.setPrice(rs.getDouble("price"));
                        product.setOriginal_price(rs.getDouble("original_price"));
                        product.setStock(rs.getInt("stock"));
                        product.setSales(rs.getInt("sales"));
                        product.setStatus(rs.getInt("status"));
                        product.setIs_deleted(rs.getInt("is_deleted"));
                        product.setCreate_time(rs.getDate("create_time"));
                        product.setUpdate_time(rs.getDate("update_time"));
                        l.add(product);
                    }
                    return l;
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }, id);
            return list.isEmpty() ? null : list.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insert(Product product) {
        String sql = "INSERT INTO `ktmall`.`kt_product`(`title`, `subtitle`, `category_id`, `category_path`, `brand`, " +
                "`main_image`, `images`, `description`, `price`, `original_price`, " +
                "`stock`, `sales`, `status`, `is_deleted`, `create_time`, `update_time`)" +
                " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW());";
        try {
            return executeUpdate(sql, product.getTitle(), product.getSubtitle(), product.getCategory_id(),
                    product.getCategory_path(), product.getBrand(), product.getMain_image(), product.getImages(),
                    product.getDescription(), product.getPrice(), product.getOriginal_price(), product.getStock(),
                    product.getSales() != null ? product.getSales() : 0, product.getStatus(),product.getIs_deleted());
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int update(Product product) {
        StringBuilder sql = new StringBuilder("update `kt_product` set ");
        List<Object> params = new ArrayList<>();
        if (product.getTitle() != null) {
            sql.append("`title` = ? ,");
            params.add(product.getTitle());
        }
        if (product.getSubtitle() != null) {
            sql.append("`subtitle` = ? ,");
            params.add(product.getSubtitle());
        }
        if (product.getCategory_id() != null) {
            sql.append("`category_id` = ? ,");
            params.add(product.getCategory_id());
        }
        if (product.getCategory_path() != null) {
            sql.append("`category_path` = ? ,");
            params.add(product.getCategory_path());
        }
        if (product.getBrand() != null) {
            sql.append("`brand` = ? ,");
            params.add(product.getBrand());
        }
        if (product.getMain_image() != null) {
            sql.append("`main_image` = ? ,");
            params.add(product.getMain_image());
        }
        if (product.getImages() != null) {
            sql.append("`images` = ? ,");
            params.add(product.getImages());
        }
        if (product.getDescription() != null) {
            sql.append("`description` = ? ,");
            params.add(product.getDescription());
        }
        if (product.getPrice() != null) {
            sql.append("`price` = ? ,");
            params.add(product.getPrice());
        }
        if (product.getOriginal_price() != null) {
            sql.append("`original_price` = ? ,");
            params.add(product.getOriginal_price());
        }
        if (product.getStock() != null) {
            sql.append("`stock` = ? ,");
            params.add(product.getStock());
        }
        if (product.getSales() != null) {
            sql.append("`sales` = ? ,");
            params.add(product.getSales());
        }
        if (product.getStatus() != null) {
            sql.append("`status` = ? ,");
            params.add(product.getStatus());
        }
        sql.append("`update_time` = NOW()  where id=? ");
        params.add(product.getId());

        try {
            return executeUpdate(sql.toString(), params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int delete(Long id) {
        String sql="update kt_product set is_deleted=1,update_time=NOW() where id=?";
        try {
            return executeUpdate(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public int updateStatus(Long id, Integer status) {
        String sql="update kt_product set status=?,update_time=now() where id=?";
        try {
            return executeUpdate(sql,status,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
